package com.msos.servlet.mainPage;



import com.fasterxml.jackson.databind.ObjectMapper;
import com.msos.model.respBean.RespBean;

import com.msos.service.ManagerService.ManagerService;
import com.msos.utils.CommonsUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Properties;

/**
 * 弟中弟：小邦
 */
@WebServlet(urlPatterns = "/servlet")
public class MainPageServletNext extends HttpServlet {
    private static final Properties SYSTEM_INFO = new Properties();
    ManagerService managerService = new ManagerService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");
        if("quit".equals(action)){
            //退出登录，并返回登录页面
            HttpSession session = req.getSession();
            session.invalidate();
            resp.sendRedirect("/MSOS/login");
        }else if("update".equals(action)){
            //修改密码
            req.getRequestDispatcher("/WEB-INF/jsp/admin/updateNext.jsp").forward(req,resp);
        }
        else {
            SYSTEM_INFO.load(MainPageServlet.class.getResourceAsStream("/system_info.properties"));
            req.setAttribute("si",SYSTEM_INFO);
            //展示主页面
            req.getRequestDispatcher("/WEB-INF/jsp/head/head.jsp").forward(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        String newPassword1 = req.getParameter("newPassword1");
        String newPassword2 = req.getParameter("newPassword2");
        Integer rs = managerService.updateManagerByPassword(name, password, newPassword1, newPassword2,req);
        RespBean respBean = null;
        if(rs == CommonsUtils.UPDATE_PASSWORD_SUCCESS){
            respBean = RespBean.ok("修改成功");
        }else if(rs == CommonsUtils.UPDATE_PASSWORD_ERROR){
            respBean = RespBean.error("新密码前后不一致");
        }else if(rs == CommonsUtils.USER_BLOCKED){
            respBean = RespBean.error("用户被封禁");
        }else if(rs == CommonsUtils.USER_NOTFOUND_OR_PASSWORD_BAD){
            respBean = RespBean.error("账户或者密码错误");
        }else {
            respBean = RespBean.error("未知错误");
        }
        resp.setContentType("application/json;charset=utf-8");
        ObjectMapper om = new ObjectMapper();
        String json = om.writeValueAsString(respBean);
        resp.getWriter().write(json);
    }
}
